import { getResponseMessage } from "@mallfoundry/client/message"
import { Role, RoleService, RoleType } from "@mallfoundry/store/role"
import { Button, Card, Col, Divider, message as antMessage, Popconfirm, Row, Table } from "antd"
import { ColumnProps } from "antd/lib/table"
import * as React from "react"
import { useState } from "react"
import { Link, useParams } from "react-router-dom"
import Page from "../../../components/page"
import { useRoles } from "../../../hooks/role"

export default function RoleList() {
  const { storeId } = useParams<{ storeId: string }>()
  const columns: ColumnProps<Role>[] = [
    {
      title: "角色名称",
      dataIndex: "name",
      key: "name",
      width: "20%",
    },
    {
      title: "描述",
      dataIndex: "description",
      key: "description",
    },
    {
      title: "员工数量",
      dataIndex: "staffsCount",
      key: "staffsCount",
      align: "center",
      width: "20%",
      render: (staffsCount: number, role) => (
        <Link to={{ pathname: `/stores/${storeId}/staffs`, search: `?role_ids=${role.id}` }} children={staffsCount}/>),
    },
    {
      title: "操作",
      key: "id",
      dataIndex: "id",
      align: "right",
      width: "20%",
      render: (id: string, role) => (
        <>
          <Link to={`/stores/${storeId}/roles/${id}`}>查看</Link>
          {
            role.type !== RoleType.Primitive
            && <>
              <Divider type="vertical"/>
              <Link to={`/stores/${storeId}/roles/${id}/edit`}>编辑</Link>
              <Divider type="vertical"/>
              <Popconfirm placement="bottomRight" title="确定要删除该角色？" onConfirm={() => deleteRole(id)}>
                <Button type="link" size="small" style={{ padding: "0" }}>删除</Button>
              </Popconfirm>
            </>
          }
        </>
      ),
    },
  ]
  const {
    loading: rolesLoading,
    elements: roles,
    refresh: refreshRoles,
  } = useRoles({ storeId })
  const [loading, setLoading] = useState(rolesLoading)

  function deleteRole(roleId: string) {
    setLoading(true)
    RoleService.deleteRole({
      storeId, id: roleId,
    })
      .then(() => {
        antMessage.success("移除成功")
      })
      .catch(error => {
        antMessage.error(getResponseMessage(error))
      })
      .finally(refreshRoles)
  }

  return (
    <div>
      <Page.Header title="角色管理" ghost={false}/>
      <Page.Content>
        <Card>
          <Row gutter={[16, 16]}>
            <Col><Button type="primary">
              <Link to={`/stores/${storeId}/roles/new`}>添加角色</Link></Button></Col>
          </Row>
          <Row>
            <Col span={24}>
              <Table rowKey="id" columns={columns} dataSource={roles} loading={loading}/>
            </Col>
          </Row>
        </Card>
      </Page.Content>
    </div>
  )
}
